import { useShallow } from 'zustand/react/shallow'
import type { RouteObject } from 'react-router-dom'
import { useRouteLoaderData } from 'react-router-dom'
import { Radio, RadioChangeEvent, Space, type MenuProps } from 'antd'
import { isEmpty } from 'lodash'
import Logo from '../logo'
import { GlobalStyles, TopNavWrapper } from './style'
import { useSysConfigStore } from '@/stores/config'
import type { ILayoutLoader } from '@/types/common'
import { useMenuStore } from '@/stores/menu'
import { getCatchRouteMeta } from '@/utils/router'
import { rootRoutes } from '@/router'
import ChangeSize from '../tools/ChangeSize'
// import Reload from '../tools/Reload'
// import LangSelect from '../tools/LangSelect'
import Screenfull from '../tools/Screenfull'
import ChangeColorScheme from '../tools/ChangeColorScheme'
import ChangeTheme from '../tools/ChangeTheme'
import Personal from '../personal'
import { SettingOutlined } from '@ant-design/icons'
import { getShopStatusApi, updateShopStatusApi } from '@/api/login'
import { message } from "@/utils/AntdGlobal";

export default function Top() {
  const { layoutMode, mainMenuBgColor, menuBgColor, mainMenuTextColor, menuTextColor, mainMenuHoverBgColor, menuHoverBgColor, mainMenuHoverTextColor, menuHoverTextColor, mainMenuActiveBgColor, menuActiveBgColor, mainMenuActiveTextColor, menuActiveTextColor, enableElementSize, enableFullscreen, enableColorScheme, enableChangeTheme, } = useSysConfigStore(useShallow(state => ({
    layoutMode: state.layoutMode,
    mainMenuBgColor: state.theme.mainMenuBgColor,
    menuBgColor: state.theme.menuBgColor,
    mainMenuTextColor: state.theme.mainMenuTextColor,
    menuTextColor: state.theme.menuTextColor,
    mainMenuHoverBgColor: state.theme.mainMenuHoverBgColor,
    menuHoverBgColor: state.theme.menuHoverBgColor,
    mainMenuHoverTextColor: state.theme.mainMenuHoverTextColor,
    menuHoverTextColor: state.theme.menuHoverTextColor,
    mainMenuActiveBgColor: state.theme.mainMenuActiveBgColor,
    menuActiveBgColor: state.theme.menuActiveBgColor,
    mainMenuActiveTextColor: state.theme.mainMenuActiveTextColor,
    menuActiveTextColor: state.theme.menuActiveTextColor,
    enableElementSize: state.toolbar.enableElementSize,
    // enablePageReload: state.toolbar.enablePageReload,
    // enableI18n: state.toolbar.enableI18n,
    enableFullscreen: state.toolbar.enableFullscreen,
    enableColorScheme: state.toolbar.enableColorScheme,
    enableChangeTheme: state.toolbar.enableChangeTheme,
  })))

  const { mainMenuActive, setMainMenuActive } = useMenuStore(useShallow(state => ({
    mainMenuActive: state.mainMenuActive,
    setMainMenuActive: state.setMainMenuActive,
  })))

  const { allMainMenu, allSubMenu } = useRouteLoaderData('layout') as ILayoutLoader

  const { t } = useTranslation()
  function getMainMenuItems(): MenuProps['items'] {
    return allMainMenu.filter(v => v.children?.length).map((k) => {
      return {
        label: t(k.title),
        key: `${k.parentIndex!}`,
        icon: <SvgIcon name={k.icon} size={16} />,
      }
    })
  }

  const clickMainMenu: MenuProps['onClick'] = (e) => {
    setMainMenuActive(Number(e.key))
  }

  // 递归获取菜单项
  function getSubMenuItems(arr: RouteObject[]): MenuProps['items'] {
    const result: MenuProps['items'] = []
    for (const item of arr) {
      let hasValidChild = false
      const filteredChildren = item.children?.length ? getSubMenuItems(item.children) : []
      // 检查过滤后的子项是否存在有效路径或有子元素
      hasValidChild = filteredChildren!.some((child: any) => child?.path || child?.children.length)
      // 当前项自身有效（即path存在） 或者 存在有效子项时，转换并保留该节点
      if (item.path || hasValidChild) {
        const newItem = {
          label: t(item.meta!.title!),
          key: item.onlyKey!,
          path: item.path,
          icon: item.meta?.icon && <SvgIcon name={item.meta?.icon} size={16} />,
          children: filteredChildren?.length ? filteredChildren : undefined,
          popupClassName: 'xt-admin-popup-menu',
        }
        // 过滤掉含有空children的顶层对象
        if (newItem.children?.length || newItem.path)
          result.push(newItem)
      }
    }
    return result
  }

  const { pathname } = useLocation()
  const curRouteMeta = getCatchRouteMeta(pathname, rootRoutes[0].children)
  const defaultActive = curRouteMeta?.activeMenu || pathname
  const nav = useNavigate()

  const clickSubMenu: MenuProps['onClick'] = (e) => {
    nav(e.key)
  }

  function customMenuClass() {
    if (layoutMode === 'topSubSideNav') {
      return {
        menuContainerBgColor: mainMenuBgColor,
        menuTextColor: mainMenuTextColor,
        menuHoverBgColor: mainMenuHoverBgColor,
        menuHoverTextColor: mainMenuHoverTextColor,
        menuActiveBgColor: mainMenuActiveBgColor,
        menuActiveTextColor: mainMenuActiveTextColor,
        darkMenuContainerBgColor: 'var(--xt-main-menu-bg-color)',
        darkMenuTextColor: 'var(--xt-main-menu-text-color)',
        darkMenuHoverBgColor: 'var(--xt-main-menu-hover-bg-color)',
        darkMenuHoverTextColor: 'var(--xt-main-menu-hover-text-color)',
        darkMenuActiveBgColor: 'var(--xt-main-menu-active-bg-color)',
        darkMenuActiveTextColor: 'var(--xt-main-menu-active-text-color)',
      }
    }
    else if (layoutMode === 'onlyTopNav') {
      return {
        menuContainerBgColor: menuBgColor,
        menuTextColor,
        menuHoverBgColor,
        menuHoverTextColor,
        menuActiveBgColor,
        menuActiveTextColor,
        darkMenuContainerBgColor: 'var(--xt-sub-menu-bg-color)',
        darkMenuTextColor: 'var(--xt-sub-menu-text-color)',
        darkMenuHoverBgColor: 'var(--xt-sub-menu-hover-bg-color)',
        darkMenuHoverTextColor: 'var(--xt-sub-menu-hover-text-color)',
        darkMenuActiveBgColor: 'var(--xt-sub-menu-active-bg-color)',
        darkMenuActiveTextColor: 'var(--xt-sub-menu-active-text-color)',
      }
    }
  }
  const menuClass = customMenuClass()
  const [value, setValue] = useState<number>();
  const [status, setStatus] = useState<number>();
  // 获取营业状态
  const getStatus = async () => {
    const res = await getShopStatusApi()
    setValue(res.data)
    setStatus(res.data)
  }
  useEffect(() => {
    if (layoutMode === 'topSubSideNav') {
      function findCurItemByPath(path: string, allSubMenu: RouteObject[]): RouteObject | undefined {
        if (isEmpty(allSubMenu))
          return undefined
        for (const item of allSubMenu) {
          if (item.path === path)
            return item

          if (!isEmpty(item.children)) {
            const res = findCurItemByPath(path, item.children!)
            if (res)
              return res
          }
        }
      }
      setMainMenuActive(findCurItemByPath(pathname, allSubMenu)?.parentIndex ?? 0)
    }
    getStatus()
  }, [allSubMenu, layoutMode, pathname, setMainMenuActive])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    getStatus()
    setIsModalOpen(true);
  };

  const handleOk = async () => {
    await updateShopStatusApi(value)
    message.success("修改状态成功")
    getStatus()
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };


  const onChange = (e: RadioChangeEvent) => {
    setValue(e.target.value);
  };
  return (
    <TopNavWrapper className="h-[var(--xt-top-nav-height)] flex flex-shrink-0 items-center px-4" $customMenuClass={menuClass}>
      <GlobalStyles $customMenuClass={menuClass} />
      <Logo className="mr-4 text-xl" />
      {status === 1 && <Button type="primary" danger>
        营业中
      </Button>}
      {status === 0 && <Button type="default">
        打烊中
      </Button>}
      {false && <ConfigProvider theme={{
        components: {
          Menu: {
            activeBarHeight: 0,
            horizontalItemBorderRadius: 8,
            iconMarginInlineEnd: 5, // 图标与文字间距
          },
        },
      }}
      >
        {layoutMode === 'topSubSideNav' && (
          <Menu className="xt-menu flex-1" mode="horizontal" selectedKeys={[`${mainMenuActive}`]} items={getMainMenuItems()} onClick={clickMainMenu} />
        )}
        {layoutMode === 'onlyTopNav' && (
          <Menu className="xt-menu flex-1" mode="horizontal" selectedKeys={[defaultActive]} items={getSubMenuItems(allSubMenu)} onClick={clickSubMenu} />
        )}
      </ConfigProvider>}
      <div className="ml-auto flex items-center">
        <Button type="primary" icon={<SettingOutlined />} onClick={showModal}>
          营业状态设置
        </Button>
        {enableElementSize && <ChangeSize className="mr-2 color-white" />}
        {/* { enablePageReload && <Reload className="mr-2" /> } */}
        {/* { enableI18n && <LangSelect className="mr-2 color-white" /> } */}
        {enableFullscreen && <Screenfull className="mr-2 color-white" />}
        {enableColorScheme && <ChangeColorScheme className="mr-2 color-white" />}
        {enableChangeTheme && <ChangeTheme className="mr-2 color-white" />}
        <Personal />
      </div>
      <Modal title="营业状态设置" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} centered>
        <Radio.Group onChange={onChange} value={value} buttonStyle='outline'>
          <Space direction="horizontal">
            <Radio.Button value={1}>
              营业中
            </Radio.Button>
            <Radio.Button value={0}>打烊中</Radio.Button>
          </Space>
        </Radio.Group>
        <div className='mt-2'>
          <div className='mt-1'>营业中：当前餐厅处于营业状态，自动接收任何订单，可点击打烊进入店铺打烊状态。</div>
          <div className='mt-1'>打烊中：当前餐厅处于打烊状态，仅接受营业时间内的预定订单，可点击营业中手动恢复营业状态。</div>
        </div>
      </Modal>
    </TopNavWrapper>
  )
}
